package com.kinon.market.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.market.sqlbean.BaseGoods;
import com.kinon.market.sqlbean.GoodsBean;
import com.kinon.market.tools.HttpTools;
import com.kinon.market.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;

/**
 * Created by luohao on 2017-07-31.
 */

public class GetMakemealService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        getGoods();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 获得订单
     */
    private void getGoods() {
        HttpTools httpTools = new HttpTools(getApplicationContext());
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        httpTools.backupGetGoods(token, new JsonGetGoods());

    }

    private class JsonGetGoods extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                if (code) {
//                    Toast.makeText(getApplicationContext(),"获取商品信息成功",
//                            Toast.LENGTH_SHORT).show();
                    //删除数据库表中的所有数据
                    DataSupport.deleteAll(GoodsBean.class);
                    Gson gson = new Gson();
                    BaseGoods base = gson.fromJson(response.toString(), BaseGoods.class);
                    ArrayList<GoodsBean> list = base.getData();
                    DataSupport.saveAll(list);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
        }
    }
}
